package com.gitee.feizns.quickstart.zxing;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import lombok.SneakyThrows;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * 条形码
 * @author feizns
 * @since 2025/4/25
 */
public class Barcode {

    /**
     * 生成条形码
     * @param barcodeText 条形码文本
     * @param width 宽度
     * @param height 高度
     * @return {@link BufferedImage }
     */
    public static BufferedImage generate(String barcodeText, int width, int height) {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        Code128Writer barcodeWriter = new Code128Writer();
        BitMatrix bitMatrix = barcodeWriter.encode(barcodeText, BarcodeFormat.CODE_128, width, height, hints);
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }

    @SneakyThrows
    public static void main(String[] args) {
        BufferedImage image = Qrcode.generate("HELLO", 400, 80);
        ImageIO.write(image, "png", Files.newOutputStream(Paths.get("D:\\tmp.png")));
    }

}
